/**
 * Copyright (c) 2010 icer He <icerhe@gmail.com>
 */
package me.linkcn.ydtxl.client.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.linkcn.ydtxl.client.Consts;
import me.linkcn.ydtxl.client.R;
import me.linkcn.ydtxl.client.sync.object.Group;
import me.linkcn.ydtxl.client.util.ContactListItemAdapter;
import me.linkcn.ydtxl.client.util.ContactHelper;
import me.linkcn.ydtxl.client.util.Util;

import com.fsck.k9.activity.Accounts;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author icer.He
 *
 */
public class MainActivity extends Activity {
	
    static long selectedGroupId = 0;
    static String selectedGroupTitle = "";
	
	private GroupListItemAdapter gAdapter;
	private static final Handler groupHandler = new Handler();
	private void refreshGroup() {
		groupHandler.post(new Runnable() {
			@Override
			public void run() {
				gAdapter.notifyDataSetChanged();
			}
		});
    }
	
	public static void launchSelf(Context c){
		Intent intent = new Intent(c, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
		c.startActivity(intent);
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState)  {

    	super.onCreate(savedInstanceState);
        Log.d(Consts.TAG, "MainActivity create");
        //初始化主画面
        show();

    }
    
    private void show() {
    	setContentView(R.layout.main);  
    	
    	//绑定按钮
    	//添加画面
	    final Button addContact = (Button) findViewById(R.id.addContact);
	    addContact.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {		
				MainActivity.this.showDialog(GROUP_CONTRACT_DIALOG);
			}
        });
	    
		//多选画面
	    final Button multi = (Button) findViewById(R.id.multi);
	    multi.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {		
				Intent intent = new Intent(MainActivity.this, MultiActivity.class);
				startActivity(intent);
			}
        });
	    
	    //收藏联系人画面
	    final Button fav = (Button) findViewById(R.id.fav);
	    fav.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {		
				Intent intent = new Intent(MainActivity.this, FavActivity.class);
				startActivity(intent);
			}
        });
	    
	    //邮件(暂时)
	    final Button mail = (Button)findViewById(R.id.mail);
	    mail.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {		
				Intent intent = new Intent(MainActivity.this, Accounts.class);
				startActivity(intent);
			}
        });
    	
    	//显示分组列表
    	final ListView glist = (ListView) findViewById(R.id.group_list);
    	Cursor cursor = getContentResolver().query(Groups.CONTENT_URI,null,Groups.DELETED+"=0",null,null);
    	//用当前activity管理curosr,activity结束的时候curosr也关闭
    	startManagingCursor(cursor);
    	List<Group> localGroupList = new ArrayList<Group>();
    	//分组"全部"
    	localGroupList.add(ContactHelper.getAllGroup(this));
    	//其他分组
    	for (cursor.moveToFirst();!(cursor.isAfterLast());cursor.moveToNext()) {  
    		Log.d("GROUP_NAME", cursor.getString(cursor.getColumnIndex(Groups.TITLE)));
    		Log.d("GROUP_ID", String.valueOf(cursor.getLong(cursor.getColumnIndex(Groups._ID))));
    		Log.d("VERSION", String.valueOf(cursor.getLong(cursor.getColumnIndex(Groups.VERSION))));
    		Log.d("SYS_ID", String.valueOf(cursor.getLong(cursor.getColumnIndex(Groups.SYSTEM_ID))));
    		Log.d("ACCOUNT_NAME", String.valueOf(cursor.getLong(cursor.getColumnIndex(Groups.ACCOUNT_NAME))));
    		Log.d("GROUP_VISIBLE", String.valueOf(cursor.getLong(cursor.getColumnIndex(Groups.GROUP_VISIBLE))));
    		Log.d("GROUP_DELETE", String.valueOf(cursor.getLong(cursor.getColumnIndex(Groups.DELETED))));
    		localGroupList.add(ContactHelper.getGroup(cursor));
    	} 
    	
    	gAdapter = new GroupListItemAdapter(this, R.layout.group_item, cursor);
        glist.setAdapter(gAdapter);
    	
    	//显示全部联系人列表
    	final ListView list = (ListView) findViewById(R.id.contacts_list);
    	String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
	        + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
	        + Contacts.DISPLAY_NAME + " != '' ))";
    	Cursor c =
	        getContentResolver().query(Contacts.CONTENT_URI, Consts.CONTACTS_SUMMARY_PROJECTION, select,
	        null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    	startManagingCursor(c);
        ContactListItemAdapter adapter = new ContactListItemAdapter(this, R.layout.contacts_item, c);
        list.setAdapter(adapter);
    }

    private final class GroupListItemAdapter extends ResourceCursorAdapter {

        public GroupListItemAdapter(Context context, int layout, Cursor c) {
            super(context, layout, c);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            final GroupListItemCache cache = (GroupListItemCache) view.getTag();
            long groupId = cursor.getLong(cursor.getColumnIndex(Groups._ID));
            String groupName = cursor.getString(cursor.getColumnIndex(Groups.TITLE));
            
            cache.id = groupId;
            if (Consts.groupName.containsKey(groupName)) {
            	cache.nameView.setText(Consts.groupName.get(groupName));
            } else {
            	cache.nameView.setText(groupName);
            }
            
            view.setOnClickListener(new OnClickListener() {//点击分组动作

				@Override
				public void onClick(View v) {
					//显示选中组中的联系人
					//Toast.makeText(MainActivity.this,"Id:"+cache.id+" Name:"+cache.nameView.getText(), Toast.LENGTH_LONG).show();
					showContactList(cache.id);
				}
            	
            });
            
            view.setOnLongClickListener(new OnLongClickListener(){//长按分组动作
				@Override
				public boolean onLongClick(View arg0) {
					selectedGroupId = cache.id;
					selectedGroupTitle = cache.nameView.getText().toString();
					showDialog(CHANGE_GROUP_DIALOG);
					return true;
				}
            	
            });
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = super.newView(context, cursor, parent);
            GroupListItemCache cache = new GroupListItemCache();
            cache.nameView = (TextView) view.findViewById(R.id.group_name);
            view.setTag(cache);

            return view;
        }
    }
    
    /**
     * 显示联系人列表
     * @param groupId
     */
    private void showContactList(long groupId) {
    	final ListView list = (ListView) findViewById(R.id.contacts_list);
    	
    	if (5 == groupId) { //收藏
    		String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
		        + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
		        + Contacts.DISPLAY_NAME + " != '' )) AND ("
		        + Contacts.STARRED + "=1)";
		        
			Cursor c =
		        getContentResolver().query(Contacts.CONTENT_URI, Consts.CONTACTS_SUMMARY_PROJECTION, select,
		        null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
			startManagingCursor(c);
		    ContactListItemAdapter adapter = new ContactListItemAdapter(this, R.layout.contacts_item, c);
		    list.setAdapter(adapter);
    	} else {
	    	Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, 
	    			  new String[] { ContactsContract.Data.RAW_CONTACT_ID },
	    			  ContactsContract.Data.MIMETYPE+" = '"+GroupMembership.CONTENT_ITEM_TYPE
	    			  +"' AND "+ContactsContract.Data.DATA1+"="+ groupId, 
	    			  null, null);
	    	StringBuilder inSelectionBff = new StringBuilder(RawContacts._ID).append(" IN ( 0");
	    	for (cursor.moveToFirst();!(cursor.isAfterLast());cursor.moveToNext()) {      		
	    		inSelectionBff.append(',').append(cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID)));
	    	}
	    	inSelectionBff.append(')');
	    	cursor.close();
	    	
	    	Cursor contactIdCursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,
	    			  new String[] { ContactsContract.RawContacts.CONTACT_ID }, inSelectionBff.toString(), null, null);
	    	inSelectionBff = new StringBuilder(Contacts._ID).append(" IN ( 0");
	    	for (contactIdCursor.moveToFirst();!(contactIdCursor.isAfterLast());contactIdCursor.moveToNext()) {      		
	    		inSelectionBff.append(',').append(contactIdCursor.getLong(contactIdCursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID)));
	    	}
	    	inSelectionBff.append(')');
	    	contactIdCursor.close();
	    	
	    	
	    	String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
		        + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
		        + Contacts.DISPLAY_NAME + " != '' )) AND "
		        + inSelectionBff.toString();
			Cursor c =
		        getContentResolver().query(Contacts.CONTENT_URI, Consts.CONTACTS_SUMMARY_PROJECTION, select,
		        null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
			startManagingCursor(c);
		    ContactListItemAdapter adapter = new ContactListItemAdapter(this, R.layout.contacts_item, c);
		    list.setAdapter(adapter);
    	}
    	
    }
    
    final static class GroupListItemCache {
    	public long id;
        public TextView nameView;
    }    
    
	private static final int PERFERENCES = 0; //设置
	private static final int ABOUT = 1; //关于
	private static final int EXIT = 2; //退出
    /**
     * Menu菜单
     */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
        menu.add(0, PERFERENCES, 1, R.string.menu_preferences);
        menu.add(0, ABOUT,       2, R.string.menu_about);
        menu.add(0, EXIT,       3, R.string.menu_exit);
		return true;
	}
	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case PERFERENCES:
                //startActivity(new Intent(this, SetAlarm.class));
            	Toast.makeText(getApplicationContext(), "功能尚未完成",
            		     Toast.LENGTH_SHORT).show();
                return true;
            case ABOUT:
                showDialog(ABOUT_DIALOG);
                return true;
            case EXIT:
            	showDialog(EXIT_DIALOG);
            	return true;
            default:
                return false;
        }
    }
    
	private static final int ABOUT_DIALOG = 0; //关于对话框
	private static final int EXIT_DIALOG = 1; //退出对话框
	private static final int GROUP_CONTRACT_DIALOG =2; //添加对话框
	private static final int ADD_GROUP_DIALOG = 3; //添加分组对话框
	private static final int CHANGE_GROUP_DIALOG = 4; //组管理对话框
	private static final int EDIT_GROUP_DIALOG = 5; //修改分组名对话框
	private static final int DISMISS_GROUP_DIALOG = 6; //解散组管理对话框
    
    @Override
    protected Dialog onCreateDialog(int id) {
    	switch(id) {
    	case ABOUT_DIALOG: //关于
            return new AlertDialog.Builder(MainActivity.this)
            .setTitle(R.string.menu_about)
            .setMessage(R.string.text_about)
            .setNeutralButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked Something so do some stuff */
                }
            })
            .create();
    	case EXIT_DIALOG: //退出
    		return new AlertDialog.Builder(MainActivity.this)
            .setTitle(R.string.menu_exit)
            .setMessage(R.string.text_exit)
            .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    finish();
                }
            })
            .setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked Cancel so do some stuff */
                }
            })
            .create();
    	case GROUP_CONTRACT_DIALOG: //添加组/联系人
            return new AlertDialog.Builder(MainActivity.this)
            .setTitle(R.string.add_contract)
            .setItems(R.array.add_group_contract, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    if (0==which) {//分组
                    	showDialog(ADD_GROUP_DIALOG);
                    } else if (1==which) {//联系人
                    	Intent intent = new Intent(Intent.ACTION_INSERT);
        				intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
        				//intent.putExtra(ContactsContract.Intents.Insert.NAME, "icer");
        				//intent.putExtra(ContactsContract.Intents.Insert.PHONE, "123456");
                        startActivity(intent);
                    }
                }
            })
            .create();
    	case ADD_GROUP_DIALOG: //添加组
            LayoutInflater factory = LayoutInflater.from(this);
            final View addGroupView = factory.inflate(R.layout.dialog_add_group, null);
            return new AlertDialog.Builder(MainActivity.this)
                .setTitle(R.string.add_group_title)
                .setView(addGroupView)
                .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	EditText groupNameView = (EditText)addGroupView.findViewById(R.id.group_title);
                        String gName = groupNameView.getText().toString();
                        if (gName.length()>0) {
                        	//添加分组
                        	ContentResolver cr = MainActivity.this.getContentResolver();
                        	ContentValues groupValues = new ContentValues();
                        	groupValues.put(ContactsContract.Groups.TITLE, gName);
                        	cr.insert(ContactsContract.Groups.CONTENT_URI, groupValues);
                        	//刷新组列表
                        	refreshGroup();
                        } else {
                        	Toast.makeText(getApplicationContext(), "组名不能为空.",
                       		     Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        /* 啥都不干 */
                    }
                })
                .create();
    	case CHANGE_GROUP_DIALOG: //修改/解散组
            return new AlertDialog.Builder(MainActivity.this)
            .setTitle(R.string.change_group_title)
            .setItems(R.array.change_group_list, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    if (0==which) {//修改分组
                    	showDialog(EDIT_GROUP_DIALOG);
                    } else if (1==which) {//解散分组
                    	ContentResolver cr = MainActivity.this.getContentResolver();
                    	cr.delete(Groups.CONTENT_URI,Groups._ID+"="+selectedGroupId,null);
                    }
                }
            })
            .create();
    	case EDIT_GROUP_DIALOG: //修改
            LayoutInflater fac = LayoutInflater.from(this);
            final View editGroupView = fac.inflate(R.layout.dialog_add_group, null);
            EditText groupTitle = (EditText)editGroupView.findViewById(R.id.group_title);
            groupTitle.setText(selectedGroupTitle);
            
            AlertDialog.Builder builder =new AlertDialog.Builder(MainActivity.this);
            final AlertDialog dialog;
            builder
            .setTitle(R.string.edit_group_title)
            .setView(editGroupView)
            .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	EditText groupNameView = (EditText)editGroupView.findViewById(R.id.group_title);
                    String gName = groupNameView.getText().toString();
                    if (gName.length()>0) {
                    	//修改组名
                    	Util.dismissDialog(dialog);
                    	ContentResolver cr = MainActivity.this.getContentResolver();
                    	ContentValues groupValues = new ContentValues();
                    	groupValues.put(ContactsContract.Groups.TITLE, gName);
                    	cr.update(ContactsContract.Groups.CONTENT_URI, groupValues, Groups._ID+"="+selectedGroupId, null);
                    	//刷新组列表
                    	refreshGroup();
                    } else {
                    	Util.keepDialog(dialog);
                    	Toast.makeText(getApplicationContext(), "组名不能为空.",
                   		     Toast.LENGTH_SHORT).show();
                    }
                }
            })
            .setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	Util.dismissDialog(dialog);
                }
            });
            dialog = builder.create();
            
            return dialog;
    	}
    	return null;
    }
}
